package com.power.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.power.config.AliyunOSSConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;

/**
 * @Description 文件上传
 * @Author dingchunlin
 * @Date 2024/07/13 21:49
 * @Version 1.0.0
 */
@Api(tags = "文件上传接口管理")
@RestController
@RequestMapping("/admin/file")
public class FileUploadController {

    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    /**
     * 上传单个文件接口
     *
     * @param file 上传的文件
     * @return 上传成功路径
     */
    @ApiOperation(value = "单个文件上传接口")
    @PostMapping("/upload/element")
    public String uploadFile(MultipartFile file) {
        // 填写Bucket名称
        String bucketName = aliyunOSSConfig.getBucketName();
        // 以天为单位的文件夹名称
        String newFolderName = DateUtil.format(new Date(), "yyyy-MM-dd");
        // 以时间戳作为文件名称
        String newFileName = DateUtil.format(new Date(), "HHmmssSSS");
        // 获取源文件的后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String objectName = newFolderName + "/" + newFileName + suffix;

        // 创建OSSClient实例。
        URL url = null;
        OSS ossClient = new OSSClientBuilder().build(aliyunOSSConfig.getEndpoint(), aliyunOSSConfig.getAccessKeyId(), aliyunOSSConfig.getAccessKeySecret());
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());
            // 上传文件
            ossClient.putObject(putObjectRequest);
            // 创建文件的访问地址
            url = ossClient.generatePresignedUrl(bucketName, objectName, DateUtil.offsetDay(new Date(), 365 * 10));
        } catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url.toString();
    }

}
